import type { Router } from 'vue-router'
import { RouteLocationRaw } from 'vue-router'
import { appConfig } from '../config/app';
import { login, nprogress, setCache } from '../index'
import { setDocumentTitle } from '../util';
import { currentRoute, currentRouter } from './current'
import { listenerRouteChange, setRouteEmitter } from './listener'


export const setupGuard = (router: Router): void => {
  currentRouter.value = router
  router.beforeEach((to, from): void => {
    currentRoute.value = to
    setRouteEmitter(to)
    if (to.path !== from.path) {
      nprogress.start()
    }
  })
  router.afterEach(() => nprogress.done())
}

export const back = async (): Promise<void> => currentRouter.value?.back()

export const to = async (to: RouteLocationRaw, replace?: boolean): Promise<void> => {
  if (currentRouter.value) {
    if (replace) {
      await currentRouter.value.replace(to)
    } else {
      await currentRouter.value.push(to)
    }
  } else {
    console.warn('router: 当前路由器没有初始化')
  }
}

export const setupLoginGuard = (router: Router): void => {
  router.beforeEach((to, from, next): void | Promise<void> => (to.meta.any ? next() : login.loginCheck(to.meta, next)))
}

listenerRouteChange(({ meta }): void => {
  setCache('redirect_uri', location.href)
  meta.title && setDocumentTitle(`${meta.title} - ${appConfig.app.title}`)
}, true)
